//
//  MVFullViewController.m
//  wind
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 李金明. All rights reserved.
//

#import "MVFullViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface MVFullViewController ()

@property (nonatomic, retain) UIView *MvPlayView;// 播放器容器
@property (nonatomic, retain) AVPlayer *player;// 播放器对象
@property (nonatomic, retain) UIButton *playBtn;// 播放/暂停按钮

@property (nonatomic, retain) UILabel *currentL;// 当前时间
@property (nonatomic, retain) UILabel *totalL;// 总时长
@property (nonatomic, retain) UIButton *tempBtn;// mv中间的开始按钮
@property (nonatomic, retain) UIProgressView *progress;// 缓冲进度条
@property (nonatomic, retain) UIView *tempV;// 放播放/暂停按钮的view
@property (nonatomic, assign) BOOL isLocked;//锁屏状态
@property (nonatomic, retain) UIButton *lockBtn; // 锁屏按钮

@end

@implementation MVFullViewController

- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0)
{
//    if (self.isLocked == YES) {
//        return NO;
//    } else {
    return YES;
//    }
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

- (void)setSlider:(UISlider *)slider
{
    if (_slider != slider) {
        [_slider release];
        _slider = [slider retain];
    }
        [self.player play];
}

- (void)dealloc
{
    [_mvStr release];
    [_MvPlayView release];
    [_player release];
    [_playBtn release];
    [_slider release];
    [_currentL release];
    [_totalL release];
    [_lockBtn release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor redColor];
    
    self.isLocked = NO;
    
    [self createMvPlayView];
    
    
}

- (void)createMvPlayView
{
    // 创建播放器容器
    self.MvPlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    self.MvPlayView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.MvPlayView];
    [_MvPlayView release];
    
    // 创建播放器层
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
    [self.MvPlayView.layer addSublayer:playerLayer];

    
    self.tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tempBtn setImage:[UIImage imageNamed:@"iconfont-iconfontbofang"] forState:UIControlStateNormal];
    [self.tempBtn addTarget:self action:@selector(tempBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.tempBtn.hidden = YES;
    [self.MvPlayView addSubview:self.tempBtn];
    [self.tempBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(self.MvPlayView);
        make.size.mas_equalTo(CGSizeMake(50, 50));
        
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 10, 40, 40);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.MvPlayView addSubview:backBtn];
    
//    self.lockBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.lockBtn setImage:[UIImage imageNamed:@"iconfont-anquandengjidaweisuoshang"] forState:UIControlStateNormal];
//    [self.lockBtn setImage:[UIImage imageNamed:@"iconfont-anquandengjidasuoshang"] forState:UIControlStateSelected];
//    [self.lockBtn addTarget:self action:@selector(lockAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.MvPlayView addSubview:self.lockBtn];
//    [self.lockBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.centerY.equalTo(self.MvPlayView);
//        make.left.mas_equalTo(@10);
//        make.width.mas_equalTo(@40);
//        make.height.mas_equalTo(@40);
//        
//    }];
    
    self.tempV = [[UIView alloc] initWithFrame:CGRectMake(0, self.MvPlayView.frame.size.height - 50, SCREEN_HEIGHT, 50)];
    self.tempV.backgroundColor = [UIColor blackColor];
    self.tempV.alpha = 0.6;
    [self.MvPlayView addSubview:self.tempV];
    [_tempV release];
    
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playBtn.frame = CGRectMake(10, 10, 30, 30);
    [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.tempV addSubview:self.playBtn];
    
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(52, 14, SCREEN_HEIGHT - self.playBtn.frame.size.width - 30, 10)];
    self.progress.progressTintColor = [UIColor lightGrayColor];
    self.progress.trackTintColor = [UIColor whiteColor];
    [self.tempV addSubview:self.progress];
    [_progress release];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(50, 10, SCREEN_HEIGHT - self.playBtn.frame.size.width - 30, 10)];
    self.slider.minimumTrackTintColor = [UIColor blueColor];
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    [self.slider setThumbImage:[UIImage imageNamed:@"iconfont-yuandian"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.tempV addSubview:self.slider];
    [_slider release];
    
    self.currentL = [[UILabel alloc] initWithFrame:CGRectMake(50, 25, 50, 20)];
    self.currentL.text = @"00:00";
    self.currentL.textColor = [UIColor whiteColor];
    [self.tempV addSubview:self.currentL];
    [_currentL release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 25, 5, 20)];
    label.text = @"/";
    label.textColor = [UIColor whiteColor];
    [self.tempV addSubview:label];
    [label release];
    
    self.totalL = [[UILabel alloc] initWithFrame:CGRectMake(105, 25, 50, 20)];
    self.totalL.textColor = [UIColor whiteColor];
    self.totalL.text = @"00:00";
    [self.tempV addSubview:self.totalL];
    [_totalL release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.MvPlayView addGestureRecognizer:tap];
    
}

//// 锁屏按钮
//- (void)lockAction:(UIButton *)sender
//{
//    if (sender.selected == YES) {
//        self.isLocked = YES;
//        [self.lockBtn setImage:[UIImage imageNamed:@"iconfont-anquandengjidasuoshang"] forState:UIControlStateSelected];
//    } else {
//        self.isLocked = NO;
//        [self.lockBtn setImage:[UIImage imageNamed:@"iconfont-anquandengjidaweisuoshang"] forState:UIControlStateNormal];
//    }
//}

// 视频上的后退按钮
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        [self stop];
    }];
}

/**
 *  初始化播放器
 *
 *  @return 播放器对象
 */
-(AVPlayer *)player{
    if (!_player) {
        AVPlayerItem *playerItem=[self getPlayItem:0];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
        
        [self addProgressObserver];
        
        [self addObserverToPlayerItem:playerItem];
    }
    return _player;
}

/**
 *  根据视频索引取得AVPlayerItem对象
 *
 *  @param videoIndex 视频顺序索引
 *
 *  @return AVPlayerItem对象
 */
-(AVPlayerItem *)getPlayItem:(int)videoIndex{
    
    NSURL *url=[NSURL URLWithString:self.mvStr];
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
    return playerItem;
}
#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
}

#pragma mark - 监控
/**
 *  给播放器添加进度更新
 */
-(void)addProgressObserver{
    //    AVPlayerItem *playerItem=self.player.currentItem;
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 10.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        //        float total=CMTimeGetSeconds([playerItem duration]);
        if (current) {
            //            NSLog(@"%f", current);
            [self.slider setValue:current animated:YES];
            int currentTime = (int)current;
            int m = currentTime / 60;
            int s = currentTime % 60;
            NSString *strM =nil;
            NSString *strS =nil;
            if (m < 10) {
                strM = [NSString stringWithFormat:@"0%d",m];
            } else {
                strM = [NSString stringWithFormat:@"%d", m];
            }
            
            if (s < 10) {
                strS = [NSString stringWithFormat:@"0%d", s];
            } else {
                strS = [NSString stringWithFormat:@"%d", s];
            }
            self.currentL.text = [NSString stringWithFormat:@"%@:%@",strM, strS];
        }
    }];
}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay){
            //            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
            [self customVideoSlider:playerItem.duration];//设置播放进度最大值
            int totalTime = (int)CMTimeGetSeconds(playerItem.duration);
            int m = totalTime / 60;
            int s = totalTime % 60;
            NSString *strM = nil;
            NSString *strS = nil;
            if (m < 10) {
                strM = [NSString stringWithFormat:@"0%d", m];
            } else {
                strM = [NSString stringWithFormat:@"%d", m];
            }
            if (s < 10) {
                strS = [NSString stringWithFormat:@"0%d", s];
            } else {
                strS = [NSString stringWithFormat:@"%d", s];
            }
            //设置视频时长的UILabel视图显示值
            self.totalL.text = [NSString stringWithFormat:@"%@:%@", strM, strS];
            
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array=playerItem.loadedTimeRanges;
        //        CMTimeRange totleTimeRange = [array.lastObject CMTimeRangeValue];
        //        float totleSeconds = CMTimeGetSeconds(totleTimeRange.duration);
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        [self.progress setProgress:totalBuffer animated:YES];
        //        NSLog(@"共缓冲：%.2f",totalBuffer);
        
    }
}

// MV播放界面中间的button
- (void)tempBtnAction
{
    [self.player play];
    self.tempBtn.hidden = YES;
    [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
}

#pragma 点击隐藏控制view
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    if (self.tempV.hidden == YES) {
        self.tempV.hidden = NO;
    } else {
        self.tempV.hidden = YES;
    }
}

#pragma mark - UI事件
/**
 *  点击播放/暂停按钮
 *
 *  @param sender 播放/暂停按钮
 */
- (void)playAction:(UIButton *)sender
{
    //    AVPlayerItemDidPlayToEndTimeNotification
    //AVPlayerItem *playerItem= self.player.currentItem;
    if(self.player.rate==0){ //说明是暂停
        [sender setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        [self.player play];
        self.tempV.hidden = YES;
        self.tempBtn.hidden = YES;
    }else if(self.player.rate==1){//正在播放
        [self.player pause];
        [sender setImage:[UIImage imageNamed:@"iconfont-iconfontbofang"] forState:UIControlStateNormal];
        self.tempBtn.hidden = NO;
    }
}

//UISlider基本设置
- (void)customVideoSlider:(CMTime)duration {
    
    self.slider.maximumValue = CMTimeGetSeconds(duration);
    self.slider.minimumValue = 0.0;
    NSLog(@"%f", self.slider.maximumValue);
}

// slider 拖动视屏跟着动
- (void)sliderAction:(UISlider *)sender
{
    if (self.player.rate == 0) {
        
        [self.player seekToTime:CMTimeMake((int)sender.value*10, 10.0)];
        //        [self.player play];
        //        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    } else if(self.player.rate == 1) {
        [self.player pause];
        [self.player seekToTime:CMTimeMake((int)sender.value*10, 10.0)];
        [self.player play];
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    }
}

- (void)stop
{
    [self.player pause];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
